<template>
  <view class="add-mood-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-back" @tap="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="navbar-content">
        <text class="navbar-title">记录心情</text>
      </view>
      <view class="navbar-action" @tap="saveMood">
        <text class="save-text">保存</text>
      </view>
    </view>

    <!-- 心情选择 -->
    <view class="mood-section">
      <view class="section-title">今天的心情如何？</view>
      <view class="mood-grid">
        <view 
          class="mood-item" 
          v-for="mood in moodOptions" 
          :key="mood.value"
          :class="{ selected: selectedMood === mood.value }"
          @tap="selectMood(mood.value)"
        >
          <text class="mood-emoji">{{ mood.emoji }}</text>
          <text class="mood-label">{{ mood.label }}</text>
        </view>
      </view>
    </view>

    <!-- 情绪强度 -->
    <view class="intensity-section" v-if="selectedMood">
      <view class="section-title">情绪强度</view>
      <view class="intensity-slider">
        <view class="slider-track">
          <view class="slider-fill" :style="{ width: intensity + '%' }"></view>
          <view 
            class="slider-thumb" 
            :style="{ left: intensity + '%' }"
            @touchstart="onSliderStart"
            @touchmove="onSliderMove"
            @touchend="onSliderEnd"
          ></view>
        </view>
        <view class="intensity-labels">
          <text class="label-item">轻微</text>
          <text class="label-item">一般</text>
          <text class="label-item">强烈</text>
        </view>
      </view>
    </view>

    <!-- 情绪标签 -->
    <view class="tags-section">
      <view class="section-title">选择标签（可多选）</view>
      <view class="tags-grid">
        <view 
          class="tag-item" 
          v-for="tag in emotionTags" 
          :key="tag"
          :class="{ selected: selectedTags.includes(tag) }"
          @tap="toggleTag(tag)"
        >
          <text class="tag-text">{{ tag }}</text>
        </view>
      </view>
    </view>

    <!-- 文字记录 -->
    <view class="note-section">
      <view class="section-title">记录想法（可选）</view>
      <textarea 
        class="note-input"
        v-model="noteText"
        placeholder="写下今天发生的事情或内心的想法..."
        maxlength="500"
        :show-confirm-bar="false"
      ></textarea>
      <view class="char-count">{{ noteText.length }}/500</view>
    </view>

    <!-- 语音记录 -->
    <view class="voice-section">
      <view class="section-title">语音记录（可选）</view>
      <view class="voice-recorder">
        <view 
          class="record-btn" 
          :class="{ recording: isRecording }"
          @touchstart="startRecord"
          @touchend="stopRecord"
          @touchcancel="cancelRecord"
        >
          <text class="record-icon">🎤</text>
          <text class="record-text">{{ isRecording ? '录音中...' : '按住录音' }}</text>
        </view>
        <view class="voice-list" v-if="voiceRecords.length > 0">
          <view class="voice-item" v-for="(voice, index) in voiceRecords" :key="index">
            <view class="voice-info">
              <text class="voice-duration">{{ voice.duration }}s</text>
              <text class="voice-time">{{ formatTime(voice.time) }}</text>
            </view>
            <view class="voice-actions">
              <text class="play-btn" @tap="playVoice(voice)">▶️</text>
              <text class="delete-btn" @tap="deleteVoice(index)">🗑️</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="save-section">
      <button class="save-btn" @tap="saveMood" :disabled="!selectedMood">
        保存心情记录
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      selectedMood: '',
      intensity: 50,
      selectedTags: [],
      noteText: '',
      voiceRecords: [],
      isRecording: false,
      recordStartTime: 0,
      sliderMoving: false,
      moodOptions: [
        { value: 'happy', emoji: '😊', label: '开心' },
        { value: 'excited', emoji: '😆', label: '兴奋' },
        { value: 'calm', emoji: '😌', label: '平静' },
        { value: 'sad', emoji: '😢', label: '难过' },
        { value: 'angry', emoji: '😠', label: '愤怒' },
        { value: 'anxious', emoji: '😰', label: '焦虑' },
        { value: 'tired', emoji: '😴', label: '疲惫' },
        { value: 'confused', emoji: '😕', label: '困惑' }
      ],
      emotionTags: [
        '工作', '学习', '家庭', '朋友', '恋爱', '健康',
        '压力', '成就', '失望', '期待', '孤独', '感激',
        '创造', '运动', '音乐', '旅行', '美食', '阅读'
      ]
    }
  },
  
  methods: {
    goBack() {
      if (this.hasUnsavedChanges()) {
        uni.showModal({
          title: '提示',
          content: '有未保存的内容，确定要离开吗？',
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack()
            }
          }
        })
      } else {
        uni.navigateBack()
      }
    },
    
    hasUnsavedChanges() {
      return this.selectedMood || this.selectedTags.length > 0 || this.noteText || this.voiceRecords.length > 0
    },
    
    selectMood(mood) {
      this.selectedMood = mood
    },
    
    toggleTag(tag) {
      const index = this.selectedTags.indexOf(tag)
      if (index > -1) {
        this.selectedTags.splice(index, 1)
      } else {
        this.selectedTags.push(tag)
      }
    },
    
    // 滑块控制
    onSliderStart(e) {
      this.sliderMoving = true
    },
    
    onSliderMove(e) {
      if (!this.sliderMoving) return
      
      const touch = e.touches[0]
      const rect = e.currentTarget.getBoundingClientRect()
      const percent = Math.max(0, Math.min(100, ((touch.clientX - rect.left) / rect.width) * 100))
      this.intensity = Math.round(percent)
    },
    
    onSliderEnd() {
      this.sliderMoving = false
    },
    
    // 语音录制
    startRecord() {
      this.isRecording = true
      this.recordStartTime = Date.now()
      
      // 这里应该调用实际的录音API
      // uni.getRecorderManager().start()
    },
    
    stopRecord() {
      if (!this.isRecording) return
      
      this.isRecording = false
      const duration = Math.round((Date.now() - this.recordStartTime) / 1000)
      
      if (duration < 1) {
        uni.showToast({
          title: '录音时间太短',
          icon: 'none'
        })
        return
      }
      
      // 模拟语音记录
      const voiceRecord = {
        id: Date.now(),
        duration: duration,
        time: new Date(),
        path: 'mock_voice_path_' + Date.now() // 实际应该是录音文件路径
      }
      
      this.voiceRecords.push(voiceRecord)
      
      uni.showToast({
        title: '录音完成',
        icon: 'success'
      })
    },
    
    cancelRecord() {
      this.isRecording = false
    },
    
    playVoice(voice) {
      // 这里应该调用实际的播放API
      uni.showToast({
        title: '播放语音',
        icon: 'none'
      })
    },
    
    deleteVoice(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条语音记录吗？',
        success: (res) => {
          if (res.confirm) {
            this.voiceRecords.splice(index, 1)
          }
        }
      })
    },
    
    formatTime(time) {
      const now = new Date()
      const diff = now - time
      const minutes = Math.floor(diff / (1000 * 60))
      
      if (minutes < 1) return '刚刚'
      if (minutes < 60) return `${minutes}分钟前`
      
      const hours = Math.floor(minutes / 60)
      if (hours < 24) return `${hours}小时前`
      
      return `${Math.floor(hours / 24)}天前`
    },
    
    saveMood() {
      if (!this.selectedMood) {
        uni.showToast({
          title: '请选择心情',
          icon: 'none'
        })
        return
      }
      
      const moodRecord = {
        id: Date.now(),
        mood: this.selectedMood,
        intensity: this.intensity,
        tags: [...this.selectedTags],
        note: this.noteText,
        voices: [...this.voiceRecords],
        date: new Date().toISOString(),
        timestamp: Date.now()
      }
      
      try {
        let moodHistory = uni.getStorageSync('mood_history') || []
        moodHistory.unshift(moodRecord)
        
        // 只保留最近100条记录
        if (moodHistory.length > 100) {
          moodHistory = moodHistory.slice(0, 100)
        }
        
        uni.setStorageSync('mood_history', moodHistory)
        
        // 更新今日心情
        const today = new Date().toDateString()
        const todayMoods = uni.getStorageSync('today_moods') || {}
        todayMoods[today] = {
          mood: this.selectedMood,
          intensity: this.intensity,
          timestamp: Date.now()
        }
        uni.setStorageSync('today_moods', todayMoods)
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (e) {
        uni.showToast({
          title: '保存失败',
          icon: 'error'
        })
      }
    }
  }
}
</script>

<style scoped>
.add-mood-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

/* 导航栏 */
.custom-navbar {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  padding: 88rpx 40rpx 40rpx;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-back {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-back .iconfont {
  font-size: 36rpx;
}

.navbar-content {
  flex: 1;
  text-align: center;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: 600;
}

.navbar-action {
  width: 60rpx;
  text-align: right;
}

.save-text {
  font-size: 28rpx;
  opacity: 0.9;
}

/* 通用样式 */
.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 20rpx;
}

/* 心情选择 */
.mood-section {
  padding: 40rpx 30rpx;
  background: white;
  margin-bottom: 20rpx;
}

.mood-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
}

.mood-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
  border-radius: 16rpx;
  transition: all 0.3s ease;
  border: 2rpx solid transparent;
}

.mood-item.selected {
  background: var(--accent-color);
  border-color: var(--primary-color);
}

.mood-emoji {
  font-size: 48rpx;
  margin-bottom: 10rpx;
}

.mood-label {
  font-size: 24rpx;
  color: var(--text-secondary);
}

/* 情绪强度 */
.intensity-section {
  padding: 40rpx 30rpx;
  background: white;
  margin-bottom: 20rpx;
}

.intensity-slider {
  margin-top: 20rpx;
}

.slider-track {
  position: relative;
  height: 8rpx;
  background: var(--border-color);
  border-radius: 4rpx;
  margin-bottom: 20rpx;
}

.slider-fill {
  height: 100%;
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  border-radius: 4rpx;
  transition: width 0.1s ease;
}

.slider-thumb {
  position: absolute;
  top: -8rpx;
  width: 24rpx;
  height: 24rpx;
  background: white;
  border: 4rpx solid var(--primary-color);
  border-radius: 50%;
  transform: translateX(-50%);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.intensity-labels {
  display: flex;
  justify-content: space-between;
}

.label-item {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

/* 情绪标签 */
.tags-section {
  padding: 40rpx 30rpx;
  background: white;
  margin-bottom: 20rpx;
}

.tags-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.tag-item {
  padding: 12rpx 24rpx;
  background: var(--bg-secondary);
  border-radius: 20rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;
}

.tag-item.selected {
  background: var(--accent-color);
  border-color: var(--primary-color);
}

.tag-text {
  font-size: 26rpx;
  color: var(--text-secondary);
}

.tag-item.selected .tag-text {
  color: var(--primary-color);
}

/* 文字记录 */
.note-section {
  padding: 40rpx 30rpx;
  background: white;
  margin-bottom: 20rpx;
}

.note-input {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  background: var(--bg-secondary);
  border-radius: 12rpx;
  font-size: 28rpx;
  color: var(--text-primary);
  line-height: 1.5;
  border: none;
  resize: none;
}

.char-count {
  text-align: right;
  font-size: 24rpx;
  color: var(--text-tertiary);
  margin-top: 10rpx;
}

/* 语音记录 */
.voice-section {
  padding: 40rpx 30rpx;
  background: white;
  margin-bottom: 20rpx;
}

.voice-recorder {
  text-align: center;
}

.record-btn {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200rpx;
  height: 200rpx;
  background: var(--bg-secondary);
  border-radius: 50%;
  transition: all 0.3s ease;
  margin-bottom: 30rpx;
}

.record-btn.recording {
  background: #ff4757;
  transform: scale(1.1);
}

.record-icon {
  font-size: 48rpx;
  margin-bottom: 10rpx;
}

.record-text {
  font-size: 24rpx;
  color: var(--text-secondary);
}

.record-btn.recording .record-text {
  color: white;
}

.voice-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.voice-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: var(--bg-secondary);
  border-radius: 12rpx;
}

.voice-info {
  display: flex;
  flex-direction: column;
  gap: 5rpx;
}

.voice-duration {
  font-size: 28rpx;
  color: var(--text-primary);
  font-weight: 600;
}

.voice-time {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

.voice-actions {
  display: flex;
  gap: 20rpx;
}

.play-btn, .delete-btn {
  font-size: 32rpx;
  padding: 10rpx;
}

/* 保存按钮 */
.save-section {
  padding: 40rpx 30rpx;
}

.save-btn {
  width: 100%;
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  color: white;
  border: none;
  border-radius: 16rpx;
  padding: 32rpx;
  font-size: 32rpx;
  font-weight: 600;
}

.save-btn:disabled {
  background: var(--border-color);
  color: var(--text-tertiary);
}
</style>